package com.dianrui.operation.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Handler;
import android.support.v4.app.ActivityCompat;
import android.text.Editable;
import android.text.InputFilter;
import android.text.InputType;
import android.text.Spanned;
import android.text.TextWatcher;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;


import com.dianrui.operation.Constant;
import com.dianrui.operation.MyApplication;
import com.dianrui.operation.R;
import com.dianrui.operation.okhttp.XHttpRequest;
import com.dianrui.operation.util.MyUtil;
import com.dianrui.operation.util.PhoneCode;
import com.dianrui.operation.util.SharedUtil;
import com.dianrui.operation.util.StringUtils;
import com.dianrui.operation.util.ToastUtil;
import com.dianrui.operation.util.Url;
import com.dianrui.operation.view.CountDownButton;
import com.google.gson.JsonObject;

import org.json.JSONObject;

import butterknife.BindView;
import butterknife.OnClick;

public class LoginActivity extends BaseActivity {
    private int loginType = 1;
    private PhoneCode mPhoneCode;


    @BindView(R.id.act_login_new_tv_psw_login)
    TextView tvPswLogin;
    @BindView(R.id.act_login_new_line_psw_login)
    View linePswLogin;
    @BindView(R.id.act_login_new_tv_sms_login)
    TextView tvSmsLogin;
    @BindView(R.id.act_login_new_line_sms_login)
    View lineSmsLogin;

    //账号
    @BindView(R.id.act_login_new_et_account)
    EditText etAccount;
    //密码
    @BindView(R.id.act_login_new_et_psw)
    EditText etPsw;
    //验证码
    @BindView(R.id.act_login_new_et_yzm)
    EditText etYzm;
    @BindView(R.id.countdown)
    CountDownButton countdown;

    @BindView(R.id.act_login_new_ll_psw)
    LinearLayout llPsw;
    @BindView(R.id.act_login_new_line_psw)
    View linePsw;

    @BindView(R.id.act_login_new_ll_yzm)
    LinearLayout llYzm;
    @BindView(R.id.act_login_new_line_yzm)
    View lineYzm;

    @BindView(R.id.act_login_new_btn_login)
    Button btnLogin;

    @BindView(R.id.act_login_new_tv_forget_psw)
    TextView tvForgetPsw;




    @Override
    public int getContentViewId() {
        return R.layout.activity_login;
    }




    @Override
    public void initView() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_SMS)
                != PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(this, Manifest.permission.RECEIVE_SMS)
                != PackageManager.PERMISSION_GRANTED) {

            ActivityCompat.requestPermissions(this, new String[]
                    {Manifest.permission.READ_SMS, Manifest.permission.RECEIVE_SMS}, 1);

        }
        llYzm.setVisibility(View.GONE);
        lineYzm.setVisibility(View.GONE);
        countdown.setOnOperationCallBack(new CountDownButton.CountDownButtonOperationCallBack() {
            @Override
            public void onFinish() {
                countdown.millisInFuture(60000);
                countdown.setText("获取验证码");
                countdown.setTextColor(getResources().getColor(R.color.white));
            }

            @SuppressLint("SetTextI18n")
            @Override
            public void onTick(long millisUntilFinished, CountDownButton countDownButton) {
                String tickTxts = millisUntilFinished / 1000 + "秒后再试";
                countdown.setText(tickTxts);
                countdown.setTextColor(Color.WHITE);
            }

            @Override
            public void onClickFromUser(boolean isRunning, long millisUntilFinished, CountDownButton countDownButton) {
                getVerificationCode();
            }
        });
        etAccount.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (etAccount.length() > 0 && etPsw.length() > 0) {
                    btnLogin.setBackgroundResource(R.drawable.red_shape1);
                } else {
                    btnLogin.setBackgroundResource(R.drawable.gray_shape);
                }
            }
        });
        etPsw.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (etAccount.length() > 0 && etPsw.length() >= 6) {
                    btnLogin.setBackgroundResource(R.drawable.red_shape1);
                } else {
                    btnLogin.setBackgroundResource(R.drawable.gray_shape);
                }
            }
        });
        etYzm.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (etAccount.length() > 0 && etYzm.length() >= 6) {
                    btnLogin.setBackgroundResource(R.drawable.red_shape1);
                } else {
                    btnLogin.setBackgroundResource(R.drawable.gray_shape);
                }

            }
        });
        setTarget();

        mPhoneCode = new PhoneCode(this, new Handler(), etAccount.getText().toString(), new PhoneCode.SmsListener() {
            @Override
            public void onResult(String result) {
                etYzm.setText(result);
            }
        });
        // 注册短信变化监听
        getContentResolver().registerContentObserver(Uri.parse("content://sms/"), true, mPhoneCode);
        setEditTextInhibitInputSpace(etAccount);
        setEditTextInhibitInputSpace(etPsw);
        setEditTextInhibitInputSpace(etYzm);
    }

    /**
     * 首次运行弹出协议和隐私对话框判断
     **/
    private void setTarget() {
        SharedPreferences share = getSharedPreferences("FirstInfo", MODE_PRIVATE);
        SharedPreferences.Editor editor = share.edit();
        editor.putBoolean("isFirstIn", false);
        editor.apply();
    }

    @Override
    public void initData() {

    }

    private void getVerificationCode() {
        String userMobie = etAccount.getText().toString().trim();

        if (StringUtils.isEmpty(userMobie)) {
            ToastUtil.showToast(getString(R.string.mobile_empty));
            return;
        }
        if (userMobie.length() < 11) {
            ToastUtil.showToast("手机号必须是11位");
            return;
        }

        if (countdown.getmCurrentmillis() > 2000) {
            ToastUtil.showToast(countdown.getmCurrentmillis() / 1000 + "秒后再试");
            return;
        }
        showLoadingDialog("正在发送验证码中...");
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("account", etAccount.getText().toString().trim());
        try {
            XHttpRequest.getInstance().postRequest(SharedUtil.getUrl() + Url.SMS, jsonObject.toString(), new XHttpRequest.XCallBack() {
                @Override
                public void onResponse(String result) {

                    if (!StringUtils.isEmpty(result)) {
                        try {
                            final JSONObject jsonObject = new JSONObject(result);
                            if (null != jsonObject && !isFinishing()) {
                                if (Constant.DATASUCCESS.equals(jsonObject.optString("status"))) {
                                    dismissLoadingDialog();
                                    countdown.start();
                                    ToastUtil.showToast(jsonObject.optString("message"));
                                } else if ("1001".equals(jsonObject.optString("status"))) {
                                    dismissLoadingDialog();
                                    countdown.cancel();
                                    ToastUtil.showToast(jsonObject.optString("message"));
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }
                }

                @Override
                public void failedRequest(String result) {
                    dismissLoadingDialog();
                    countdown.cancel();
                    countdown.setText("获取验证码");
                    ToastUtil.showToast(getString(R.string.net_error));
                }
            });
        } catch (IllegalArgumentException e) {
            ToastUtil.showToast("域名地址不正确，请重新输入");
            e.printStackTrace();
        }
    }

    public static void setEditTextInhibitInputSpace(EditText editText){
        InputFilter filter=new InputFilter() {

            @Override
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                if(source.equals(" ")){
                    return "";
                }else {
                    return null;
                }
            }
        };
        editText.setFilters(new InputFilter[]{filter});
    }


    @OnClick({R.id.act_login_new_ll_psw_login, R.id.act_login_new_ll_sms_login, R.id.act_login_im_xx, R.id.act_login_im_xx1,
            R.id.act_login_new_tv_forget_psw, R.id.act_login_new_btn_login, R.id.act_login_new_tv_xieyi, R.id.settings})
    void click(View view) {
        switch (view.getId()) {
            //账号密码登录
            case R.id.act_login_new_ll_psw_login:
                loginType = 1;
                etAccount.setHint("请输入管理员账号");
                setViewType();
                break;
            //短信验证登录
            case R.id.act_login_new_ll_sms_login:
                loginType = 2;
                etAccount.setHint("请输入手机号");
                InputFilter[] filters = {new InputFilter.LengthFilter(11)};
                etAccount.setFilters(filters);
                setViewType();
                break;

            case R.id.act_login_im_xx:
                etAccount.setText("");
                break;
            case R.id.act_login_im_xx1:
                etPsw.setText("");
                break;

            //登录
            case R.id.act_login_new_btn_login:
                String userName = etAccount.getText().toString().trim();
                if (loginType == 1) {
                    String psw = etPsw.getText().toString().trim();
                    if (StringUtils.isEmpty(userName) || StringUtils.isEmpty(psw)) {
                        ToastUtil.showToast("用户名或密码不能为空");
                        return;
                    }
                    if (StringUtils.isEmpty(SharedUtil.getUrl())) {
                        ToastUtil.showToast("请绑定域名后再登录");
                        return;
                    }
                    loginWithPwd(userName, psw);

                } else if (loginType == 2) {
                    if (StringUtils.isEmpty(userName)) {
                        ToastUtil.showToast("请输入手机号");
                        return;
                    }
                    String yzm = etYzm.getText().toString().trim();
                    if (StringUtils.isEmpty(yzm)) {
                        ToastUtil.showToast("请输入验证码");
                        return;
                    }
                    if (StringUtils.isEmpty(SharedUtil.getUrl())) {
                        ToastUtil.showToast("请绑定域名后再登录");
                        return;
                    }
                    loginWithCode(userName, yzm);
                }
                break;
            case R.id.settings:
                JumpActivitys(BindServerActivity.class);
                break;
            case R.id.act_login_new_tv_xieyi:
                JumpActivitys(WebViewActivity.class);
                break;

            default:
                break;
        }
    }


    private void setViewType() {
        if (loginType == 1) {
            //账号密码登录
            etAccount.setText("");
            etAccount.setInputType(InputType.TYPE_CLASS_TEXT);
            tvPswLogin.setTextColor(getResources().getColor(R.color.red1));
            linePswLogin.setVisibility(View.VISIBLE);
            tvSmsLogin.setTextColor(getResources().getColor(R.color.black));
            lineSmsLogin.setVisibility(View.INVISIBLE);

            llPsw.setVisibility(View.VISIBLE);
            linePsw.setVisibility(View.VISIBLE);
            llYzm.setVisibility(View.GONE);
            lineYzm.setVisibility(View.GONE);
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            if (imm != null) {
                imm.hideSoftInputFromWindow(etAccount.getWindowToken(), 0);
            }
        } else if (loginType == 2) {
            ////短信验证登录
            etAccount.setText("");
            etAccount.setInputType(InputType.TYPE_CLASS_NUMBER);
            etAccount.setFilters(new InputFilter[]{new InputFilter.LengthFilter(11)});
            tvPswLogin.setTextColor(getResources().getColor(R.color.black));
            linePswLogin.setVisibility(View.INVISIBLE);
            tvSmsLogin.setTextColor(getResources().getColor(R.color.red1));
            lineSmsLogin.setVisibility(View.VISIBLE);

            llPsw.setVisibility(View.GONE);
            linePsw.setVisibility(View.GONE);
            llYzm.setVisibility(View.VISIBLE);
            lineYzm.setVisibility(View.VISIBLE);

            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            if (imm != null) {
                imm.hideSoftInputFromWindow(etAccount.getWindowToken(), 0);
            }
        }
    }

    //登录（只输入手机号和密码）
    //{"server":"http://wobai.nx.021dr.cn","account":"admin","token":"123456","type":1}
    private void loginWithPwd(final String userName, final String psw) {
        showLoadingDialog("正在登录中...");
        JsonObject loginJson = new JsonObject();
        loginJson.addProperty("server_name", SharedUtil.getName());
        loginJson.addProperty("server", SharedUtil.getUrl());
        loginJson.addProperty("account", userName);
        loginJson.addProperty("token", psw);
        loginJson.addProperty("device_number", MyUtil.getUniqueId(LoginActivity.this));
        loginJson.addProperty("type", 1);
        try {
            XHttpRequest.getInstance().postRequest(SharedUtil.getUrl() + Url.LOGIN, loginJson.toString(), new XHttpRequest.XCallBack() {
                @Override
                public void onResponse(String result) {
                    if (!StringUtils.isEmpty(result)) {
                        try {
                            final JSONObject jsonObject = new JSONObject(result);
                            if (null != jsonObject && !isFinishing()) {
                                if (Constant.DATASUCCESS.equals(jsonObject.optString("status"))) {
                                    dismissLoadingDialog();
                                    spUtils.put("account", jsonObject.optJSONObject("data").optString("account"));
                                    spUtils.put("nickname", jsonObject.optJSONObject("data").optString("nickname"));
                                    spUtils.put("mobile", jsonObject.optJSONObject("data").optString("mobile"));
                                    spUtils.put("email", jsonObject.optJSONObject("data").optString("email"));
                                    spUtils.put("face", jsonObject.optJSONObject("data").optString("face"));
                                    spUtils.put("alias", jsonObject.optJSONObject("data").optString("alias"));
                                    spUtils.put("scan_url", jsonObject.optJSONObject("data").optString("scan_url"));
                                    spUtils.put("menu", result);
                                    SharedUtil.setToken(jsonObject.optJSONObject("data").optString("token"));
                                    MyApplication.initJiGuangUser(jsonObject.optJSONObject("data").optString("alias"), LoginActivity.this);
                                    countdown.destroy();
                                    JumpActivitys(MainActivity.class);
                                    finish();
                                } else if ("1001".equals(jsonObject.optString("status"))) {
                                    dismissLoadingDialog();
                                    if (countdown != null) {
                                        countdown.cancel();
                                    }
                                    if (mPhoneCode != null) {
                                        getContentResolver().unregisterContentObserver(mPhoneCode);
                                    }
                                    countdown.setText(getString(R.string.getcode_txt));
                                    countdown.setTextColor(Color.WHITE);
                                    ToastUtil.showToast(jsonObject.optString("message"));

                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }

                @Override
                public void failedRequest(String result) {
                    dismissLoadingDialog();
                    ToastUtil.showToast(getString(R.string.net_error));
                }
            });
        } catch (IllegalArgumentException e) {
            ToastUtil.showToast("域名地址不正确，请重新输入");
            e.printStackTrace();
        }
    }

    //只输入手机号和验证码
    private void loginWithCode(final String userName, final String yzm) {
        showLoadingDialog("正在登录中...");
        JsonObject loginJson = new JsonObject();
        loginJson.addProperty("server_name", SharedUtil.getName());
        loginJson.addProperty("server", SharedUtil.getUrl());
        loginJson.addProperty("account", userName);
        loginJson.addProperty("token", yzm);
        loginJson.addProperty("device_number", MyUtil.getUniqueId(LoginActivity.this));
        loginJson.addProperty("type", "2");//1账户密码登录，2短信验证登录
        try {
            XHttpRequest.getInstance().postRequest(SharedUtil.getUrl() + Url.LOGIN, loginJson.toString(), new XHttpRequest.XCallBack() {
                @Override
                public void onResponse(String result) {
                    if (!StringUtils.isEmpty(result)) {
                        try {
                            final JSONObject jsonObject = new JSONObject(result);
                            if (null != jsonObject && !isFinishing()) {
                                if (Constant.DATASUCCESS.equals(jsonObject.optString("status"))) {
                                    dismissLoadingDialog();
                                    spUtils.put("account", jsonObject.optJSONObject("data").optString("account"));
                                    spUtils.put("nickname", jsonObject.optJSONObject("data").optString("nickname"));
                                    spUtils.put("mobile", jsonObject.optJSONObject("data").optString("mobile"));
                                    spUtils.put("email", jsonObject.optJSONObject("data").optString("email"));
                                    spUtils.put("alias", jsonObject.optJSONObject("data").optString("alias"));
                                    spUtils.put("menu", String.valueOf(result));
                                    SharedUtil.setToken(jsonObject.optJSONObject("data").optString("token"));
                                    MyApplication.initJiGuangUser(jsonObject.optJSONObject("data").optString("alias"), LoginActivity.this);
                                    if (countdown != null) {
                                        countdown.cancel();
                                    }
                                    if (mPhoneCode != null) {
                                        getContentResolver().unregisterContentObserver(mPhoneCode);
                                    }
                                    JumpActivitys(MainActivity.class);
                                    finish();
                                } else if ("1001".equals(jsonObject.optString("status"))) {
                                    dismissLoadingDialog();
                                    if (countdown != null) {
                                        countdown.cancel();
                                    }
                                    if (mPhoneCode != null) {
                                        getContentResolver().unregisterContentObserver(mPhoneCode);
                                    }
                                    countdown.setText(getString(R.string.getcode_txt));
                                    countdown.setTextColor(Color.WHITE);
                                    ToastUtil.showToast(jsonObject.optString("message"));
                                } else if ("1002".equals(jsonObject.optString("status"))) {
                                    dismissLoadingDialog();
                                    if (countdown != null) {
                                        countdown.cancel();
                                    }
                                    if (mPhoneCode != null) {
                                        getContentResolver().unregisterContentObserver(mPhoneCode);
                                    }
                                    countdown.setText(getString(R.string.getcode_txt));
                                    countdown.setTextColor(Color.WHITE);
                                    ToastUtil.showToast(jsonObject.optString("message"));
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }

                @Override
                public void failedRequest(String result) {
                    dismissLoadingDialog();
                    if (countdown != null) {
                        countdown.cancel();
                    }
                    if (mPhoneCode != null) {
                        getContentResolver().unregisterContentObserver(mPhoneCode);
                    }
                    countdown.cancel();
                    countdown.setText(getString(R.string.getcode_txt));
                    countdown.setTextColor(Color.WHITE);
                    ToastUtil.showToast(getString(R.string.net_error));
                }
            });
        } catch (IllegalArgumentException e) {
            ToastUtil.showToast("域名地址不正确，请重新输入");
            e.printStackTrace();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (countdown != null) {
            countdown.destroy();
        }
        if (mPhoneCode != null) {
            getContentResolver().unregisterContentObserver(mPhoneCode);
        }
    }
}
